package com.app.commond;

import com.app.commond.entity.GpsBean;
import com.app.commond.entity.LockInfoBean;
import com.app.commond.sys.AppCmd;
import com.app.commond.sys.CmdBase;
import com.app.commond.sys.CmdDevAddr;
import com.app.commond.sys.CmdFuncCode;
import com.app.exception.NotEnoughException;
import com.app.protocol.ProtocolLockInfo;
import com.app.protocol.entity.ProtocolGPS;
import com.app.redis.Publisher;
import soft.common.BConvrtUtil;
import soft.common.BytesHexStrTranslate;
import soft.common.DateUtils;
import soft.common.JSONUtil;
import soft.net.exception.DataIsNullException;

import java.text.ParseException;

/**
 * 电子锁信息上传
 *
 * 操作回复（1B,0x55）+ Cmd（1B）+LockID(4B)+Gate（1B）+ Bill (8B)+ Voltage(1B)+LockStatus
 （1B）+ MotoStatus (1B)+ cmdSRC(1B，操作源：短信 0x00,自动 0x01,键盘 0x02,手持机 0X03；
 中心 0X04；卡口 0X05；)+绝对时间（6B）
 开始    操作回复   解封成功 LockID     Gate      Bill        Voltage  LockStatus    MotoStatus  cmdSRC             指令发送时间    结束  子功能  子功能
 2A   55           90    1CE8015D   04    0000000000000000 33      60            00           04                  180929141318 23  0381   1123
 * 
 * @author fanpei
 *
 */
@AppCmd(devAddr = CmdDevAddr.OX03, funcCode = CmdFuncCode.OX03_ELockInfoUpload)
public class CmdELockInfoUpload extends CmdBase {
	private ProtocolLockInfo protocolLockInfo;// 电子锁信息
	public CmdELockInfoUpload() {
		protocolLockInfo = new ProtocolLockInfo();
	}

	@Override
	public void parse() throws Exception {
		if (protocol.getDatas() == null) {
			throw new DataIsNullException("the elock info is null");
		}
		if (protocol.getDatas().length != ProtocolLockInfo.UP_SIZE
				&& protocol.getDatas().length != (ProtocolLockInfo.UP_SIZE - 4)) {

			throw new NotEnoughException("the elock info bytes's length is not correct!"+protocol.getDatas().length);
		}
		byte[] elockbytes = new byte[ProtocolLockInfo.UP_SIZE];
		System.arraycopy(protocol.getDatas(), 0, elockbytes, 0, ProtocolLockInfo.UP_SIZE);
		if (elockbytes == null) {
			throw new DataIsNullException("elock parse,elockbytes is null!");
		}
		protocolLockInfo = new ProtocolLockInfo(elockbytes);
		protocolLockInfo.parse();
		protocolLockInfo.validate();
		sendLockInfoToMq();
	}

	@Override
	public void excute() throws Exception {
		channel.sendData(protocolLockInfo);

	}
	private void sendLockInfoToMq() throws Exception {
		LockInfoBean lockInfoBean = new LockInfoBean();
		lockInfoBean.setCmdSRC(BConvrtUtil.getLockOprSource(protocolLockInfo.getCmdSRC()));
		lockInfoBean.setLockDevID(protocol.getLockDevID());
		lockInfoBean.setLockStatus(BConvrtUtil.getLockRespStatus(protocolLockInfo.getLockStatus()));
		lockInfoBean.setSendtime(DateUtils.formatHexTime(BytesHexStrTranslate.bytesToHexFun1(protocolLockInfo.getSendtime())));
		lockInfoBean.setVoltage(protocolLockInfo.getVoltage());
		Publisher.sendLockStatus(JSONUtil.genJsonStr(lockInfoBean));
	}

}
